<template>
  <div class="startBox">
    <img src="../../assets/uploadVideo.png">

    <div class="startMain">
      <div class="startTitle"><img src="../../assets/taskIcon.png">自主上传视频文件，进行行为分析</div>

      <div class="video-upload-container">
        <div class="upload__tip">
          支持MP4格式
        </div>
      
        <!-- 老师视频上传 -->
        <div class="uplod-oneLine">
          <div class="uplod-oneLine-label">老师视频：</div>
          <div class="uplod-oneLine-right">
            <el-upload
              ref="teacherUpload"
              class="upload-demo"
              :action="''"  
              :on-change="handleTeacherFileChange"
              :file-list="teacherFileList"
              :auto-upload="false"
              :limit="1"
              :on-exceed="handleExceed"
              accept="video/mp4"
            >
              <el-button size="small" type="primary">选择</el-button>      
            </el-upload>
            <el-progress v-if="teacherProgress > 0" :percentage="teacherProgress" :stroke-width="6" text-inside />
          </div>
        </div>
        
        <!-- 学生视频上传 -->
        <div class="uplod-oneLine">
          <div class="uplod-oneLine-label">学生视频：</div>
          <div class="uplod-oneLine-right">
            <el-upload
              ref="studentUpload"
              class="upload-demo"
              :action="''" 
              :on-change="handleStudentFileChange"
              :file-list="studentFileList"
              :auto-upload="false"
              :limit="1"
              :on-exceed="handleExceed"
              accept="video/mp4"
            >
              <el-button size="small" type="primary">选择</el-button>
            </el-upload>
            <el-progress v-if="studentProgress > 0" :percentage="studentProgress" :stroke-width="6" text-inside />
          </div>
        </div>

        <!-- 上传按钮 -->
        <div class="upload-btn-container">
          <el-button 
            type="success" 
            :disabled="!canUpload || isUploading"
            :loading="isUploading" 
            @click="handleUpload" 
          >
            {{ 
              isUploading ? '上传中...' : 
              uploadCompleted ? '已上传' : '上传视频' 
            }}
          </el-button>

          <el-button 
            v-if="canUpload || isUploading || uploadCompleted" 
            type="danger"
            :disabled="false"
            @click="handleClearOrCancel"
          >
            {{ 
              isUploading ? '取消上传' : 
              uploadCompleted ? '清空视频' : '清空视频' 
            }}
          </el-button>
        </div>
      </div>

      <div class="taskIn" style="margin-top: 10px;">
        <el-form ref="form" :model="form" :rules="rules" label-width="112px" class="taskInForm">

          <el-form-item label="任务名：" prop="name">
            <el-input v-model="form.name" placeholder="请输入任务名" />
          </el-form-item>

          <el-form-item label="班级:" prop="department_id">
            <treeselect
              v-model="form.department_id"
              :options="deptOptions"
              :normalizer="normalizer"
              :disable-branch-nodes="true"
              :show-count="true"
              placeholder="请选择班级"
            />
          </el-form-item>

          <el-form-item label="ST采样时间:" prop="sampling_interval">
            <el-select v-model="form.sampling_interval" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in intervalOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="关键字:">
            <div style="display: inline-flex; align-items: center;">
              <el-input
                v-model="inputValue"
                placeholder="请输入关键字"
                size="small"
                style="width: 150px;"
                @keyup.enter.native="handleInputConfirm"
              />
              <el-button
                type="primary"
                size="small"
                style="margin-left: 6px;"
                @click="handleInputConfirm"
              >
                确定
              </el-button>
            </div>
            <div v-if="keywords.length !== 0" class="members-selectedLine">
              <el-tag
                v-for="(tag, index) in keywords"
                :key="index"
                closable
                style="margin-right: 8px"
                @close="removeKeyword(index)"
              >
                {{ tag }}
              </el-tag>
            </div>
          </el-form-item>

          <div class="btnLine">
            <div class="btnCheck" @click="startNewTask('form')">开启分析</div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request' 
import axios from 'axios' 
import { startTask } from '@/api/main'
import { listDept } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'StartClass',
  components: { Treeselect },

  data() {
    return {
      form: {},
      deptOptions: [],
      keywords: [],
      inputValue: '',

      // 上传视频
      uploadUrl: this.$API_BASE_URL + '/task/analyse/upload-videos',
      teacherFileList: [],
      studentFileList: [],
      teacherFile: null,
      studentFile: null,
      teacherProgress: 0,
      studentProgress: 0,
      isUploading: false,
      uploadCompleted: false,
      cancelTokenSource: null, 

      intervalOptions: [
        { value: 5, label: '5秒' },
        { value: 15, label: '15秒' },
        { value: 30, label: '30秒' }
      ],
      rules: {
        department_id: [
          { required: true, message: '班级不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        sampling_interval: [
          { required: true, message: '请选择采样时间', trigger: 'change' }
        ]
      }
    }
  },

  computed: {
    canUpload() {
      return !this.uploadCompleted && this.teacherFileList.length > 0 && this.studentFileList.length > 0
    }
  },

  created() {
    this.getTreeselect()
  },

  methods: {
    getTreeselect() {
      listDept().then(response => {
        this.deptOptions = response.data
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },

    handleInputConfirm() {
      const value = this.inputValue.trim()
      if (value && !this.keywords.includes(value)) {
        this.keywords.push(value)
      }
      this.inputValue = ''
    },

    removeKeyword(index) {
      this.keywords.splice(index, 1)
    },

    startNewTask(formName) {
      if (!this.form.videoStream1 || !this.form.videoStream2) {
        this.$message.error('请先上传老师和学生的视频文件！');
        return;
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.type = 3
          this.form.voice_key_words = this.keywords.join('_')
          startTask(this.form).then(response => {
            if (response.code === 20000) {
              this.$alert('已提交分析，请在任务列表中查看', '提交成功', {
                confirmButtonText: '确定',
                type: 'success',
                closeOnClickModal: false,
                closeOnPressEscape: false
              }).then(() => {
                location.reload();
              });
            }
          })
        }
      })
    },

    // 上传视频相关方法
    handleExceed(files, fileList) {
      this.$message.warning(`只能上传一个视频文件，已自动忽略多余的${files.length}个文件`)
    },

    handleTeacherFileChange(file, fileList) {
      if (file.status === 'ready') {
        this.teacherFile = file.raw;
        this.teacherFileList = fileList;
      }
    },

    handleStudentFileChange(file, fileList) {
      if (file.status === 'ready') {
        this.studentFile = file.raw;
        this.studentFileList = fileList;
      }
    },

    // 统一的清空/取消方法
    handleClearOrCancel() {
      if (this.isUploading) {
        // 情况1：上传过程中 - 取消上传
        this.cancelUpload()
      } else {
        // 情况2：上传前或上传后 - 清空视频
        this.clearVideos()
      }
    },
    
    // 取消上传（终止上传过程）
    cancelUpload() {
      if (this.isUploading && this.cancelTokenSource) {
        this.cancelTokenSource.cancel('用户取消上传')
        this.$message.info('上传已取消')
      }
    },
    
    // 清空视频（重置所有状态）
    clearVideos() {
      // 重置所有状态
      this.isUploading = false
      this.uploadCompleted = false
      this.teacherProgress = 0
      this.studentProgress = 0
      this.teacherFileList = []
      this.studentFileList = []
      this.teacherFile = null
      this.studentFile = null
      this.uploadResult = null
      this.cancelTokenSource = null
      this.form.videoStream1 = null
      this.form.videoStream2 = null
      
      // 清空上传组件
      if (this.$refs.teacherUpload) {
        this.$refs.teacherUpload.clearFiles()
      }
      if (this.$refs.studentUpload) {
        this.$refs.studentUpload.clearFiles()
      }
      
      this.$message.success('已清空，请重新选择文件')
    },
    
    // 修改上传方法，添加取消令牌
    handleUpload() {
      if (!this.canUpload) return

      this.isUploading = true
      this.uploadCompleted = false
      this.teacherProgress = 0
      this.studentProgress = 0

      // 创建取消令牌
      const CancelToken = axios.CancelToken
      this.cancelTokenSource = CancelToken.source()

      const formData = new FormData()
      formData.append('teacher_video', this.teacherFile)
      formData.append('student_video', this.studentFile)

      request({
        url: this.uploadUrl,
        method: 'post',
        data: formData,
        timeout: 0,
        cancelToken: this.cancelTokenSource.token,
        onUploadProgress: (progressEvent) => {
          if (progressEvent.total) {
            const percent = Math.floor((progressEvent.loaded / progressEvent.total) * 100)
            this.teacherProgress = percent
            this.studentProgress = percent
          }
        }
      }).then(response => {
        this.uploadResult = response
        this.form.videoStream1 = response.student_video.saved_name
        this.form.videoStream2 = response.teacher_video.saved_name
        this.isUploading = false
        this.uploadCompleted = true // 标记上传完成
        this.cancelTokenSource = null
        this.$message.success(response.message || '视频上传成功')
      }).catch(error => {
        this.isUploading = false
        this.uploadCompleted = false
        this.teacherProgress = 0
        this.studentProgress = 0
        
        // 如果是用户取消，不显示错误信息
        if (axios.isCancel(error)) {
          console.log('上传已被用户取消')
          // 取消后自动清空文件
          this.$nextTick(() => {
            this.clearVideos()
          })
          return
        }
        
        const errorMsg = error.response 
          ? (error.response.data ? error.response.data.message : error.message)
          : error.message
        this.$message.error('上传失败：' + errorMsg)
      })
    }
  }
}
</script>

<style scoped>
.startBox{
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}
.startBox img{
  width:644px;
  height: 610px;
  margin-left: 5%;
}
.startMain{
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-left: 5%;
}
.startTitle{
  font-size: 30px;
  font-weight: bold;
  display: flex;
  align-items: center;
  color: #1364c2;
  margin-bottom:30px;
}
.startTitle img{
  width:34px;
  height: 34px;
  margin:5px 10px 0 0;
}
.taskIn{
  display: flex;
  flex-direction: column;
  width:500px;
  margin-top: 20px;
  margin-left: 50px;
  position:relative
}
.btnLine{
  display: flex;
  align-items: center;
  margin-top:40px;
}
.btnCheck{
  width:210px;
  height: 52px;
  background: linear-gradient(#7abbff,#45baff);
  display: flex;
  align-items: center;
  border-radius: 26px;
  justify-content: center;
  color: #fff;
  font-size: 24px;
  font-weight: bold;
  cursor: pointer;
}
.btnCheck:hover{
  background: linear-gradient(#46baff,#45baff);
}

.video-upload-container {
  padding: 16px;
  background: #fff;
  width: 500px;
  margin-left: 50px;
  border:1px solid #dcdfe6
}

.upload-demo {
  margin-bottom: 10px; 
}
.uplod-oneLine{
  display: flex;
  border-bottom: 1px dashed #e4e7ed;
  margin-bottom: 10px;
}
.uplod-oneLine-label{
  width: 80px;
  font-size: 14px;
  line-height: 30px;
  color: #606266;
}
.uplod-oneLine-right{
  flex: 1;
  padding-right: 20px;
}
.upload__tip{
  margin-bottom: 16px;
  font-size: 14px;
  color: #666;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 14px;
}
.upload-btn-container {
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 10px;
}
.el-progress{
  margin-bottom: 10px;
}

::v-deep .el-progress__text {
  font-size: 14px;
}
</style>
<style >
.taskInForm .el-form-item {
  margin-bottom: 8px;
}
.taskInForm .el-form-item .el-form-item__label{
  width:112px;
  font-size: 14px;
  font-weight: normal;
  text-align: left;
}
.taskInForm .el-form-item .el-form-item__error{
  display: block;
  width: 100px;
  color: #ff4949;
  font-size: 12px;
  position: absolute;
  top: 8px;
  left: 102%;
}
.members-selectedLine{
  background: #fff;
  border:1px solid #dcdfe6;
  margin-top:6px;
  padding:6px 8px;
  border-radius: 5px;
}
.members-selectedLine span{
  margin-right: 8px;
}
</style>